package com.ds.infra.rpc.example.provider.service;

import com.ds.infra.rpc.annotation.RpcService;
import com.ds.infra.rpc.example.api.ProductService;
import com.ds.infra.rpc.example.api.dto.ProductDTO;
import com.ds.infra.rpc.example.api.exception.ApiException;
import com.ds.infra.rpc.example.api.exception.ErrorCode;
import com.ds.infra.rpc.example.provider.dao.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RpcService(version = "1.0", group = "product")
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public ProductDTO getProductById(Long id) throws ApiException {
        return productRepository.findById(id)
                .orElseThrow(() -> new ApiException(ErrorCode.PRODUCT_NOT_FOUND));
    }

    @Override
    public List<ProductDTO> getAllProducts() throws ApiException {
        return productRepository.findAll();
    }

    @Override
    public boolean reduceStock(Long productId, int quantity) throws ApiException {
        System.out.println("======扣减库存：productId = " + productId + ", quantity = " + quantity + "======");
        ProductDTO product = getProductById(productId);
        if (product.getStock() < quantity) {
            throw new ApiException(ErrorCode.PRODUCT_STOCK_INSUFFICIENT);
        }
        product.setStock(product.getStock() - quantity);
        productRepository.save(product);
        return true;
    }

    @Override
    public List<ProductDTO> batchQueryProducts(List<Long> productIds) throws ApiException {
        return productRepository.findAllById(productIds);
    }
}
